﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestIEnumlator01 : MonoBehaviour
{
    //方案一，执行StartCoroutine，将返回这个协同程序的引用，需要的时候直接StopCoroutine(这个引用);
    Dictionary<string, Coroutine> CoroutineDic = new Dictionary<string, Coroutine>();
    //消息输出字典，用于Debug
    Dictionary<string, string> MessageDic = new Dictionary<string, string>() {
        { "a", "Test04" },
        { "s", "Test05" },
        { "d", "Test06" }
    };
    void Start()
    {
        //模拟运行协程
        CoroutineDic.Add("a", StartCoroutine(Test04()));
        CoroutineDic.Add("s", StartCoroutine(Test05(1f)));
        CoroutineDic.Add("d", StartCoroutine(Test06("测试", 1f)));
    }

    private void Update()
    {
        if (Input.anyKeyDown)
        {
            string name = Input.inputString;
            if (CoroutineDic.ContainsKey(name))
            {
                StopCoroutine(CoroutineDic[name]);
                CoroutineDic.Remove(name);
                Debug.Log(string.Format("我按下了{0}键，字典还有{1}个对象，注意看协程{2}还有输出不？", name, CoroutineDic.Count, MessageDic[name]));
            }
        }
    }
    //以下协程均为测试用，为了便于观察，均为死循环且定时均为1秒
    IEnumerator Test04()//不带参数协程
    {
        while (true)
        {
            yield return new WaitForSeconds(1f);
            Debug.Log("我是Test04:" + Time.realtimeSinceStartup);
        }
    }
    IEnumerator Test05(float _DelayTime)//带一个参数的协程
    {
        while (true)
        {
            yield return new WaitForSeconds(_DelayTime);
            Debug.Log("我是Test05:" + Time.realtimeSinceStartup);
        }
    }
    IEnumerator Test06(string msg, float delayTime)//带两个参数的协程
    {
        while (true)
        {
            yield return new WaitForSeconds(delayTime);
            Debug.Log("我是Test06:" + Time.realtimeSinceStartup + "传入字符串为:" + msg);
        }
    }
}

